package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.ResponseResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.CashHistory;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.Withdraw;
import com.ruoyi.system.dto.ApiByPhoneAddDto;
import com.ruoyi.system.dto.ApiOrderReceiveAddDto;
import com.ruoyi.system.service.CashHistoryService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.OrderService;
import com.ruoyi.system.vo.ApiPayResultVo;
import com.ruoyi.system.vo.SumAmountVo;
import com.ruoyi.web.controller.common.CheckTimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "管理后台:订单管理")
@RestController
@RequestMapping("admin/order")
public class AdminOrderController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Resource
    private ISysConfigService configService;

    private String moneyCol = "amount";
    @Log(title = "指定用户创建订单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "指定用户创建订单")
    @PostMapping("createOrderByPhone")
    public ResponseResult<ApiPayResultVo> createOrderByPhone(@RequestBody ApiByPhoneAddDto apiChinaOrderReceiveAddDto) {
        Long userId = this.getUserId();
        apiChinaOrderReceiveAddDto.setMerchantId(userId);
        apiChinaOrderReceiveAddDto.setMerchantOrderNo(System.currentTimeMillis() + "" + userId);
        apiChinaOrderReceiveAddDto.setNotifyUrl(configService.selectConfigByKey("zfbNotifyUtl") + "/api/order/notifyMe");
        return this.setSuccessResult(orderService.createOrderByPhone(apiChinaOrderReceiveAddDto));
    }
    @Log(title = "创建订单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "创建订单")
    @PostMapping("createOrder")
    public ResponseResult<ApiPayResultVo> createOrder(@RequestBody ApiOrderReceiveAddDto apiChinaOrderReceiveAddDto) {
        Long userId = this.getUserId();
        apiChinaOrderReceiveAddDto.setMerchantId(userId);
        apiChinaOrderReceiveAddDto.setMerchantOrderNo(System.currentTimeMillis() + "" + userId);
        apiChinaOrderReceiveAddDto.setNotifyUrl(configService.selectConfigByKey("zfbNotifyUtl") + "/api/order/notifyMe");
        return this.setSuccessResult(orderService.apiOrder(apiChinaOrderReceiveAddDto, "sys"));
    }
    @Log(title = "管理员导出订单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "管理员导出订单")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order) {
        this.checkAdmin();
        CheckTimeUtil.checkTime(order.getParams());
        List<Order> list = orderService.list(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "订单数据");
    }


    @ApiOperation(value = "订单列表")
    @GetMapping("list")
    public ResponseResult<List<Withdraw>> list(Order orderPay) {
        SysUser user = this.getLoginUser().getUser();
        // Order orderPay = new Order();
        if (!StrUtil.equals(user.getRole(), "admin")) {
            orderPay.setMerchantId(user.getUserId());
            orderPay.setMerchantId(user.getUserId());

        }
        // orderPay.setChannelCode(domain.getChannelCode());
        Map<String, Object> map = new HashMap<>();
        this.startPage();
        List<Order> list = orderService.findList(orderPay);
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        DateTime yestodayBegin = DateUtil.offsetDay(beginOfDay, -1);

        orderPay.setOrderStatus(OrderStatusEnum.success.getValue());
        BigDecimal yestoday = orderService.sum(moneyCol, orderPay, yestodayBegin, beginOfDay);
        BigDecimal today = orderService.sum(moneyCol, orderPay, beginOfDay, new Date());
        BigDecimal totalAmount = orderService.sum(moneyCol, orderPay, null, null);

        DateTime thisMonth = DateUtil.beginOfMonth(new Date());
        DateTime dateTime = DateUtil.offsetMonth(thisMonth, -1);
        BigDecimal thisMonthAmount = orderService.sum(moneyCol, orderPay, thisMonth, new Date());
        BigDecimal preMonthAmount = orderService.sum(moneyCol, orderPay, dateTime, thisMonth);
        SumAmountVo groupAmount = orderService.sumByUserId(orderPay.getUserId());
        SumAmountVo sumAmountVo = new SumAmountVo();
        sumAmountVo.setTodayAmount(today);
        sumAmountVo.setYestodayAmount(yestoday);
        sumAmountVo.setTotalAmount(totalAmount);
        sumAmountVo.setPreMonthAmount(preMonthAmount);
        sumAmountVo.setThisMonthAmount(thisMonthAmount);
        map.put("sumAmountVo", sumAmountVo);
        map.put("groupAmount", groupAmount);
        map.put("pageResult", this.getPageResult(list));
        return this.setSuccessResult(map);
    }

    @Log(title = "管理员确认收款", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "确认收款")
    @GetMapping("finish")
    public ResponseResult finish(Long id) {
        checkAdmin();
        orderService.finish(id);
        return this.setSuccessResult();
    }
    @Log(title = "管理员释放订单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "释放订单")
    @GetMapping("release")
    public ResponseResult release(Long id) {
        checkAdmin();
        orderService.release(id);
        return this.setSuccessResult();
    }
    @Log(title = "管理员驳回订单，不释放资金", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "驳回订单")
    @GetMapping("reject")
    public ResponseResult reject(Long id) {
        checkAdmin();
        orderService.reject(id);
        return this.setSuccessResult();
    }

    @Log(title = "管理员补发通知", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "补发通知")
    @GetMapping("notice")
    public ResponseResult notice(Long id) {
        checkAdmin();
        Order check = this.orderService.check(id);
        orderService.notice(check);
        return this.setSuccessResult();
    }

    @ApiOperation(value = "超时补单")
    @GetMapping("reduce")
    public ResponseResult reduce(String orderNo) {
        checkAdmin();
        Order check = this.orderService.getByOrderNo(orderNo);
        orderService.reduce(check.getUserId(), check.getId());
        return this.setSuccessResult();
    }

    @Resource
    CashHistoryService cashHistoryService;


    private static String[] surnames = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
            "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
            "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷",
            "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和",
            "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒",
            "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季"};
    private static String[] names = {"碧凡", "夏菡", "曼香", "若烟", "半梦", "雅绿", "冰蓝", "灵槐", "平安", "书翠", "翠风", "香巧", "代云", "友巧", "听寒",
            "梦柏", "醉易", "访旋", "亦玉", "凌萱", "访卉", "怀亦", "笑蓝", "春翠", "靖柏", "书雪", "乐枫", "念薇", "靖雁", "寻春", "恨山", "从寒", "忆香",
            "觅波", "静曼", "凡旋", "新波", "代真", "新蕾", "雁玉", "冷卉", "紫山", "千琴", "恨天", "傲芙", "盼山", "怀蝶", "冰兰", "问旋", "从南", "白易",
            "问筠", "如霜", "半芹", "寒雁", "怜云", "寻文", "谷雪", "乐萱", "涵菡", "海莲", "傲蕾", "青槐", "冬儿", "易梦", "惜雪", "宛海", "之柔", "夏青"};


    @ApiOperation(value = "释放未退回")
    @GetMapping("updateUserCash")
    public ResponseResult updateUserCash() {
        PageDomain pageDomain = new PageDomain();
        boolean b = true;
        while (b) {
            List<Order> list = orderService.findList(new Order(), pageDomain);
            for (int i = 0; i < list.size(); i++) {
                Order order = list.get(i);
                if (order.getCreateTime().getTime() < DateUtil.parseDateTime("2023-12-08 00:00:00").getTime()) {
                    b = false;
                    break;
                }
                CashHistory cashHistory = new CashHistory();
                cashHistory.setOrderNo(order.getOrderNo());
                List<CashHistory> cashHistories = cashHistoryService.findList(cashHistory);
                List<String> collect = cashHistories.stream().map(c -> c.getRemark()).collect(Collectors.toList());
                if (CollectionUtil.contains(collect, "超时补单") &&
                        !CollectionUtil.contains(collect, "释放冻结资金")) {//如果包含超时补单
                  //  orderService.release(order.getId());

                }


            }
            pageDomain.setPageNo(pageDomain.getPageNo() + 1);

        }


        return this.setSuccessResult();
    }

    @ApiOperation(value = "更新游戏区服")
    @GetMapping("updateGamer")
    public ResponseResult updateGamer() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageSize(100);
        boolean b = true;
        while (b) {
            List<Order> list = orderService.findList(new Order(), pageDomain);
            if (CollectionUtil.isEmpty(list)) {
                b=false;
                break;
            }
            List<Order> result = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Order order = list.get(i);
                if(StrUtil.isNotBlank(order.getServiceNo())){
                    System.out.println(order.getId()+"已有值");
                    continue;
                }
                Order domain = new Order();
                domain.setId(order.getId());
                domain.setUpdateTime(order.getUpdateTime());
                String serviceNo = "微信" + (RandomUtil.randomInt(3) + 1) + "区/服务器" + (RandomUtil.randomInt(15) + 1);
                String realname = surnames[(int) (Math.random() * surnames.length)] + names[(int) (Math.random() * names.length)];
                domain.setGamer(realname);
                domain.setServiceNo(serviceNo);
                result.add(domain);
            }
            orderService.updateBatchById(result);
            pageDomain.setPageNo(pageDomain.getPageNo() + 1);

        }


        return this.setSuccessResult();
    }


}
